package com.service.impl;

import com.entity.User;
import com.mapper.UserMapper;
import com.service.IUserService;
import com.util.MD5Util;
import com.util.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * Author: foshou.zhang
 * Date : 2016/3/6 0006
 * Time :下午 4:26
 */
@Service
public class UserServiceImpl implements IUserService {
    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
    @Resource
    private UserMapper userMapper;

    public User getUserById(Integer id) {
        try {
            return userMapper.getUserById(id);
        } catch (Exception e) {
            log.debug(Message.ERROR, e);
        }
        return null;
    }

    public User getUserByUsername(String username) {
        try {
            User user = userMapper.getUserByUsername(username);
            return user;
        } catch (Exception e) {
            System.out.println("e=" + e);
            log.debug(Message.ERROR, e);
        }
        return null;
    }

    public void insertUser(User user) {
        try {
            String password = MD5Util.encode(user.getPassword());
            System.out.println("encodePassword = " + password);
            userMapper.insertUser(user.getUsername(), password, user.getCategory());
        } catch (Exception e) {
            log.debug(Message.ERROR, e);
        }
    }

    public boolean checkUsername(String username) {
        User user = userMapper.getUserByUsername(username);
        if (null != user) {
            return true;
        }
        return false;
    }

    public boolean login(User user) {
        String username = user.getUsername();
        User user1 = getUserByUsername(username);
        boolean flag = MD5Util.compare(user1.getPassword(), user.getPassword());
        if (null != user1 && flag) {
            return true;
        }
        return false;
    }

    ;
}
